#!/bin/bash
primary_display=""
last_display=""
xrandr --auto
if [[ "x`cat /proc/acpi/button/lid/LID/state|grep open`" = "x" ]]; then 
   displays=(DP-1-2-1 DP-1-2-3 DP-2-1 DP-2-3 )
   lipclosed=(eDP-1-1 eDP-1 )
   echo "NOTICE: lip is closed, so close internal display [ ${lipclosed[*]} ]"
else
   displays=(eDP-1-1 DP-1-2-1 DP-1-2-3 eDP-1 DP-2-1 DP-2-3 )
   lipclosed=(NULL )
   echo "NOTICE: lip is open"
fi

for d in ${lipclosed[*]}
do
    xrandr --output $d --off
done

for d in ${displays[*]}
do
    xrandr --output $d --auto
    #echo "testing: $d"
    opened_displays=`xrandr | egrep "\sconnected.*[0-9]+x[0-9]+" | awk '{print $1}' `
    #echo "opened display: $opened_displays "
    if [[ "${opened_displays[@]}" =~ "$d" ]]; then
        #echo "$d is open...."
        if [[ "x$last_display" = "x" ]]; then
            echo "setting $d as primary...." 
	    xrandr --output $d --auto --primary 
        else
            echo "setting $d left-of $last_display"
	    xrandr --output $d --auto --left-of $last_display
        fi
	last_display="$d"
    else
        echo "Error: $d is not open"
    fi 
done


